<?php

use Illuminate\Database\Capsule\Manager as DB;

class SmsController extends CommonController
{
    protected $authExcept = ['send', 'key'];

    public function sendAction()
    {
        $params = $this->getPost();
        try {
            Validate::check($params, [
                'mobile' => ['func'=>'isPhone', 'msg'=>'手机号'],
                'event' => ['role'=>'required', 'msg'=>'事件'],
                //'smsKey' => ['role'=>'required', 'msg'=>'短信密钥'],
            ]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        if (!Cache::exists($params['smsKey'])) {
            //throw new Exception("短信密钥不存在");
        }
        //forget($params['smsKey']);
        if (\smscodeModel::query()->where('mobile', $params['mobile'])->whereDate('created_at', date('Y-m-d'))->count()>5) {
            throw new Exception("今日可发送次数已超限");
        }
        \app\service\sms::send($params['mobile'], $params['event']);
        json(['code' => 1, 'msg' => '发送成功']);
    }

    public function keyAction()
    {
        $params = $this->getPost();
        Validate::check($params, [
            'mobile' => ['func'=>'isPhone', 'msg'=>'手机号'],
        ]);
        $keyStr = 'Sms_' . randStr(8);
        remember($keyStr, 300, function () use($params){
            return $params['mobile'];
        });
        json(['code' => 1, 'msg' => '发送成功', 'data'=>$keyStr]);
    }
    
}
